package com.tony.xml;

import javafx.scene.transform.Rotate;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * @version V1.0  </br>
 * @ClassName DOM4JStrToXml </br>
 * @Description TODO  </br>
 * @Author tonywang</br>
 * @DATE 3/8/2019 10:29 AM</br>
 */
public class DOM4JStrToXml {
    public static void main(String[] args) {

    }

    public void demo1() throws DocumentException {
        // 创建saxreader对象
        SAXReader reader = new SAXReader();
        // 读取一个文件，把这个文件转换成Document对象
        Document document = reader.read(new File("src//a.xml"));
        // 获取根元素
        Element root = document.getRootElement();
        // 把文档转换字符串
        String docXmlText = document.asXML();
        System.out.println(docXmlText);
        System.out.println("---------------------------");
        // csdn元素标签根转换的内容
        Element csdn = root.element("csdn");
        String csdnXmlText = csdn.asXML();
        System.out.println(csdnXmlText);
        System.out.println("---------------------------");
        // 获取java元素标签 内的内容
        Element java = csdn.element("java");
        System.out.println(java.asXML());
    }

    /**
     * 创建一个document对象 往document对象中添加节点元素 转存为xml文件
     *
     * @throws Exception
     */
    public void demo2() throws IOException {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("csdn");
        Element java = root.addElement("java");
        java.setText("java班");
        Element ios = root.addElement("IOS");
        ios.setText("IOS班");
        writer(document);

    }

    /**
     * 把document对象写入新的文件
     *
     * @param document
     * @throws Exception
     */
    public void writer(Document pDocument) throws IOException {
        // 排版缩进的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置编码
        format.setEncoding("UTF-8");
        // 创建XMLWriter对象,指定了写出文件及编码格式
        // XMLWriter writer = new XMLWriter(new FileWriter(new
        // File("src//a.xml")),format);
        XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(new File("src//a.xml")), "UTF-8"), format);
        // 写入
        writer.write(pDocument);
        // 立即写入
        writer.flush();
        // 关闭操作
        writer.close();
    }

}
